﻿/********************************************************
 * Module Name    : Get Text accoding to a language
 * Purpose        : Get Message Text from database accoding to a language and 
 *                  fill and create a dictionary from it
 * Chronological Development
 * Veena Pandey     
  ******************************************************/
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using VAdvantage.Classes;
using VAdvantage.DataBase;
using System.Data;
using VAdvantage.SqlExec;
using VAdvantage.Framework;

namespace VAdvantage.Common
{
    /// <summary>
    /// Fills a dictinary with all message keywords and its values according to a language.
    /// </summary>
    public class GetMessage
    {
        // declare variables
        private static CCache<string, string> dic = null;
        private static string lineSeparator = Utility.Envs.NL + Utility.Envs.NL; //"\r\n\r\n"; //separate by line
        private static string lastkey = "";
        private static string mainMessage = "";

        /// <summary>
        /// Fills the Dictinary with message keywords and its values
        /// </summary>
        /// <returns>void</returns>
        /// <author>Veena Pandey</author>
        public static void FillDictionary()
        {
            //dic.ContainsKey -- checks whethr it contains the key
            //dic.TryGetValue -- get values of the key
            string sqlQry = "";
            //if (  GlobalVariable.AD_LANGUAGE == "en-US")
            if (Utility.Envs.IsBaseLanguage(Utility.Envs.GetContext(), "AD_language"))
            {
                // if english language is selected
                sqlQry = "SELECT Value,MsgText,MsgTip,AD_Message_ID FROM AD_Message";
            }
            else
            {
                // if language other than english is selected
                sqlQry = "SELECT m.Value,t.MsgText,t.MsgTip,m.AD_Message_ID FROM AD_Message_Trl t,AD_Message m WHERE m.AD_Message_ID=t.AD_Message_ID"
                    + " AND t.AD_Language='" + Utility.Envs.GetAD_Language(Utility.Envs.GetContext()) + "'";
            }
            // execute query and store in dataset
            DataSet ds = ExecuteQuery.ExecuteDataset(sqlQry);
            // if dataset contains any data
            if (ds.Tables[0].Rows.Count > 0)
            {
                // get total count
                int totRows = ds.Tables[0].Rows.Count;
                // initialise dictionary object
                dic = new CCache<string, string>("AD_Message", 100);
                string msgText = "";
                // for every record get keyword and its value from dataset
                for (int iCnt = 0; iCnt < totRows; iCnt++)
                {
                    // get message text
                    msgText = ds.Tables[0].Rows[iCnt]["MsgText"].ToString();
                    if (ds.Tables[0].Rows[iCnt]["MsgTip"].ToString() != "")
                    {
                        // concat message tip if exists with message text with a separator
                        msgText += lineSeparator + ds.Tables[0].Rows[iCnt]["MsgTip"].ToString();
                    }
                    // add the concatenated text with its keyword in dictinary
                    dic.Add(ds.Tables[0].Rows[iCnt]["Value"].ToString(), msgText);
                    msgText = "";
                }
            }
        }

        /// <summary>
        /// Get message text of keyword specified according to the selected language
        /// </summary>
        /// <param name="keyName">Keyword Name</param>
        /// <returns>string (message text)</returns>
        /// <author>Veena Pandey</author>
        public static string GetMessageText(string keyName)
        {
            return GetMessageText(keyName, true);
        }

        /// <summary>
        /// Get message/tip text of keyword specified according to the selected language
        /// </summary>
        /// <param name="keyName">Keyword Name</param>
        /// <param name="isMsgText">if true returns Message Text, if false returns Message Tip
        ///     and if null then returns both message text and tip.</param>
        /// <returns>string (message text)</returns>
        /// <author>Veena Pandey</author>
        public static string GetMessageText(string keyName, bool? isMsgText)
        {
            string message = "";
            // check if the last fetched keyword is the same as this keyword
            if (lastkey != keyName)
            {
                // if not, get its value from the function
                mainMessage = GetFullValue(keyName);
                // update the lastkey by this keyword name
                lastkey = keyName;
            }
            message = mainMessage;
            // if isMsgText=null
            if (isMsgText == null)
            {
                // return message text and tip(if exits) both
                return message;
            }
            // if the value of keyword is not empty
            if (message != "")
            {
                //get the position of separator from the value of keyword
                int iPos = message.IndexOf(lineSeparator);
                // if separator does not exists in the value
                if (iPos == -1)
                {
                    // if true
                    if ((bool)isMsgText)
                    {
                        //return message text
                        return message;
                    }
                    else
                    {
                        //else return blank
                        return "";
                    }
                }
                // else if separator exists in the value
                else
                {
                    // if true
                    if ((bool)isMsgText)
                    {
                        //get message text
                        message = message.Substring(0, iPos);
                    }
                    else
                    {
                        //else message tip
                        int iStart = iPos + lineSeparator.Length;
                        message = message.Substring(iStart);
                    }
                }
            }
            else
            {
                // if key not found/value is empty return the keyword name
                message = keyName;
                //ErrorLog.FillErrorLog("GetMessage.GetMessageText", "NOT FOUND " + keyName, "", Message.MessageType.WARNING);
            }
            return message;
        }

        /// <summary>
        /// Get message from dictionary object according to keyword specified
        /// </summary>
        /// <param name="keyName">Keyword Name</param>
        /// <returns>string (message text)</returns>
        /// <author>Veena Pandey</author>
        static string GetFullValue(string keyName)
        {
            // if dictinary has some record
            if (dic == null || dic.Count == 0)
            {
                // if not, again fill the dictinary
                FillDictionary();
            }
            string strRetValue = "";
            // if dictinary has some record
            if (dic != null)
            {
                //check whether dictinary contains the keyword
                if (dic.ContainsKey(keyName))
                {
                    // if yes, return the value associated with this keyword
                    strRetValue = dic[keyName];
                }
                else
                {
                    ErrorLog.FillErrorLog("GetMessage.GetFullValue", "Not Found: " + keyName, "", Message.MessageType.WARNING);
                }
            }
            return strRetValue;
        }

        /// <summary>
        /// "Translate" text
        /// </summary>
        /// <pre>
        ///     Check Context
        ///     Check AD_Element.ColumnName	->	Name
        ///     Check AD_Message.AD_Message ->	MsgText
        /// </pre>
        /// <param name="ctx">context</param>
        /// <param name="text"></param>
        /// <returns>translated text or original text if not found</returns>
        /// <author>Veena Pandey</author>
        public static string Translate(VAdvantage.Classes.Context ctx, string text)
        {
            // check if text is null
            if (text == null || text.Length == 0)
                return text;
            // get text value from context if exists
            string s = (string)ctx.GetContext(text);
            if (s != null && s.Length > 0)
                return s;

            // return translated text
            return Translate(GlobalVariable.AD_LANGUAGE, ctx.IsSOTrx(), text);
        }

        public static string Translate(Utility.Ctx ctx, string text)
        {
            // check if text is null
            if (text == null || text.Length == 0)
                return text;
            // get text value from context if exists
            string s = (string)ctx.GetContext(text);
            if (s != null && s.Length > 0)
                return s;

            // return translated text
            return Translate(GlobalVariable.AD_LANGUAGE, ctx.IsSOTrx(), text);
        }

        /// <summary>
        /// "Translate" text
        /// </summary>
        /// <pre>
        ///     Check AD_Element.ColumnName	->	Name
        ///     Check AD_Message.AD_Message ->	MsgText
        /// </pre>
        /// <param name="ad_language">language</param>
        /// <param name="isSOTrx">sales order context</param>
        /// <param name="text">Text - MsgText or Element Name</param>
        /// <returns>translated text or original text if not found</returns>
        /// <author>Veena Pandey</author>
        public static string Translate(string ad_language, bool isSOTrx, string text)
        {
            //// check if text is null
            //if (text == null || text.Equals(""))
            //    return "";
            //string AD_Language = ad_language;
            //// check language exists
            //if (AD_Language == null || AD_Language.Length == 0)
            //    AD_Language = GlobalVariable.AD_BASE_LANGUAGE;

            ////	Check AD_Element
            //string retStr = GetElement(AD_Language, text, isSOTrx);
            //if (!retStr.Equals(""))
            //    return retStr.Trim();

            ////	Check AD_Message
            //retStr = GetMessageText(text, true);
            //if (retStr != null)
            //    return retStr;

            ////	Nothing found
            ////if (!text.startsWith("*"))
            ////    s_log.warning("NOT found: " + text);
            return text;
        }

        /// <summary>
        /// Translate elements enclosed in "@" (at sign)
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="text">text</param>
        /// <returns>translated text or original text if not found</returns>
        public static String ParseTranslation(VAdvantage.Classes.Context ctx, String text)
        {
            if (text == null || text.Length == 0)
                return text;

            String inStr = text;
            String token;
            StringBuilder outStr = new StringBuilder("");

            int i = inStr.IndexOf("@");
            while (i != -1)
            {
                outStr.Append(inStr.Substring(0, i));			// up to @
                inStr = inStr.Substring(i + 1);	// from first @

                int j = inStr.IndexOf("@");						// next @
                if (j < 0)										// no second tag
                {
                    inStr = "@" + inStr;
                    break;
                }

                token = inStr.Substring(0, j);
                outStr.Append(Translate(ctx, token));			// replace context

                inStr = inStr.Substring(j + 1);	// from second @
                i = inStr.IndexOf("@");
            }

            outStr.Append(inStr);           					//	add remainder
            return outStr.ToString();
        }

        /// <summary>
        /// Translate elements enclosed in "@" (at sign)
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="text">text</param>
        /// <returns>translated text or original text if not found</returns>
        public static String ParseTranslation(Utility.Ctx ctx, String text)
        {
            if (text == null || text.Length == 0)
                return text;

            String inStr = text;
            String token;
            StringBuilder outStr = new StringBuilder("");

            int i = inStr.IndexOf("@");
            while (i != -1)
            {
                outStr.Append(inStr.Substring(0, i));			// up to @
                inStr = inStr.Substring(i + 1);	// from first @

                int j = inStr.IndexOf("@");						// next @
                if (j < 0)										// no second tag
                {
                    inStr = "@" + inStr;
                    break;
                }

                token = inStr.Substring(0, j);
                outStr.Append(Translate(ctx, token));			// replace context

                inStr = inStr.Substring(j + 1);	// from second @
                i = inStr.IndexOf("@");
            }

            outStr.Append(inStr);           					//	add remainder
            return outStr.ToString();
        }
        /// <summary>
        /// Get Translation for Element
        /// </summary>
        /// <param name="ad_language">language</param>
        /// <param name="ColumnName">column name</param>
        /// <param name="isSOTrx">if false PO terminology is used (if exists)</param>
        /// <returns>Name of the Column or "" if not found</returns>
        public static String GetElement(String ad_language, String ColumnName, bool isSOTrx)
        {
           return GetElement( ColumnName, isSOTrx);
        }

        /// <summary>
        /// Get Translation for System Element
        /// </summary>
        /// <param name="ColumnName">column name</param>
        /// <returns>Name of the Column or "" if not found</returns>
        public static String GetElement(String ColumnName)
        {
            return GetElement(ColumnName, true);
        }

        /// <summary>
        /// Get Translation for Element
        /// </summary>
        /// <param name="ColumnName">column name</param>
        /// <param name="isSOTrx">is sales transaction</param>
        /// <returns>Name of the Column or "" if not found</returns>
        public static String GetElement(String ColumnName, bool isSOTrx)
        {
            return Utility.Msg.GetElement(Utility.Envs.GetCtx(), ColumnName, isSOTrx);
        }
    }
}

